package cn.xjt.screenShare.util;

import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

public class ImageUtil {
    public static byte[] catScreen() throws IOException, AWTException {
        // 获取屏幕尺寸
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        // 创建需要截取的矩形区域
        Rectangle rect = new Rectangle(0, 0, screenSize.width, screenSize.height);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        // 截屏操作
        BufferedImage bufImage = new Robot().createScreenCapture(rect);
//        压缩
        BufferedImage compress = Thumbnails.of(bufImage).size(1920,1080).asBufferedImage();
        ImageIO.write(compress, "png", bao);
        return bao.toByteArray();
    }

    //byte数组到图片到硬盘上
    public static void byte2image(byte[] data,String path){
        if(data.length<3||path.equals("")) return;//判断输入的byte是否为空
        try{
            FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));//打开输入流
            imageOutput.write(data, 0, data.length);//将byte写入硬盘
            imageOutput.close();
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }
}
